package com.zzh.lib.views;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;

import com.zzh.lib.dialog.R;
import com.zzh.lib.views.listener.HDragViewCallback;

import androidx.annotation.NonNull;
import androidx.annotation.Px;
import androidx.customview.widget.ViewDragHelper;

/**
 * Created by ZZH on 2022/2/18.
 *
 * @Date: 2022/2/18
 * @Email: zzh_hz@126.com
 * @QQ: 1299234582
 * @Author: zzh
 * @Description: 可拖拽控件，子控件可以拖拽
 */
public class HDragViewLayout extends FrameLayout {
    public static final String tag = "HDragViewLayout";
    private boolean debug = false;

    public void setDebug(boolean debug) {
        this.debug = debug;
    }

    /**
     * 滑动滑块
     */
    protected View mLockBtn;
    /**
     * 拽托帮助类
     */
    private ViewDragHelper mViewDragHelper;

    HDragViewCallback mHDragViewCallback;

    public HDragViewCallback getDragViewCallback() {
        return mHDragViewCallback;
    }

    public HDragViewLayout setDragViewCallback(HDragViewCallback HDragViewCallback) {
        mHDragViewCallback = HDragViewCallback;
        return this;
    }

    public HDragViewLayout(Context context) {
        this(context, null);
    }

    public HDragViewLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HDragViewLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    protected void init(Context context, AttributeSet attrs, int defStyleAttr) {

        mViewDragHelper = ViewDragHelper.create(this, 0.5f, mHDragViewCallback);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        //找到需要拽托的滑块
        mLockBtn = findViewById(R.id.h_drag_view);
        if (mLockBtn == null) {
            throw new NullPointerException("必须要有一个滑动滑块");
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        //将onInterceptTouchEvent委托给ViewDragHelper
        return mViewDragHelper.shouldInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //将onTouchEvent委托给ViewDragHelper
        mViewDragHelper.processTouchEvent(event);
        return true;
    }

    @Override
    public void computeScroll() {
        super.computeScroll();
        //判断是否移动到头了，未到头则继续
        if (mViewDragHelper != null) {
            if (mViewDragHelper.continueSettling(true)) {
                invalidate();
            }
        }
    }
}
